#include "LinkStack.hpp"
#include <cstdlib>
#include <stack/LinkStack.hpp>


Status  initStack(LinkStackPtr ptr)
{
    ptr->base =(Node*)malloc(sizeof(Node));
    if (!ptr->base) exit(OVERFLOW);
    ptr->base->next=NULL;
    ptr->top=ptr->base;
    ptr->size=0;
    return  OK;
}

Status  destoryStack(LinkStackPtr ptr)
{
    Node *pre=ptr->base->next;
    while (pre)
    {
        Node *temp=pre;
        pre=pre->next;
        free(temp);
    }
    return OK;
}
Status  clearStack(LinkStackPtr ptr)
{
    Node *pre=ptr->base->next;
    while (pre)
    {
        Node *temp=pre;
        pre=pre->next;
        free(temp);
    }
    ptr->base->next=NULL;
    ptr->size=0;
    ptr->top=ptr->base;
    return OK;
}
Status   stackEmpty(LinkStackPtr ptr)
{
    if ( ptr->size == 0 )
    {
        return OK;
    }
    else
    {
        return ERROR;
    }
}
long   stackLength(LinkStackPtr ptr)
{
    return ptr->size;
}

Status  getTop(LinkStackPtr ptr,ElemType &e)
{
    e=ptr->top->data;
    return OK;
}

Status  push(LinkStackPtr ptr,ElemType e)
{
    Node *node= (Node*) malloc(sizeof(Node));
    node->next=NULL;
    node->data=e;
    ptr->top->next=node;
    ptr->top=node;
    ptr->size++;
    return OK;
}
Status  pop(LinkStackPtr ptr,ElemType& e)
{
    if (ptr->top== ptr->base ) return ERROR;
    Node *pre=ptr->base;
    if ( pre->next != ptr->top)
    {
        pre=pre->next;
    }
    e=ptr->top->data;
    ptr->top=pre;
    ptr->size++;
    return OK;
}
Status  stackTraverse(LinkStackPtr ptr,Status (*visit)(ElemType))
{
    Node *pre=ptr->base;

    while( ptr->size -- >= 0)
    {
        visit(pre->next->data);
        pre=pre->next;
    }
    return OK;
}